<template>
  <div class="order-list">
    <div class="top">
      <div class="topfix">
        <div class="search-wrap">
          <div class="search-box">
            <img class="search-icon" src="../../assets/image/icon/icon-search.png" alt="">
            <input v-model="visitorNameOrPhone" placeholder="请输入访客姓名或手机号码" type="text" @input="searchInput">
            <img
              v-show="visitorNameOrPhone"
              class="clear-icon"
              src="../../assets/image/icon/icon-clear.png"
              alt=""
              @click="visitorNameOrPhone = ''"
            >
          </div>
          <div class="search-btn" @click="keyWordSearch">搜索</div>
        </div>
        <div class="filter-wrap">
          <div v-for="(item, index) in filterList" :key="index" class="filter-item" @click="changeFilter(index)">
            <span :class="index === checkedIndex ? 'filter-checked' : ''">{{ item }}</span>
          </div>
        </div>
      </div>
    </div>

    <van-list
      v-model="loading"
      :finished="finished"
      :immediate-check="false"
      :finished-text="list.length > 0 ? '没有更多了' :''"
      loading-text=" "
      @load="onLoad"
    >
      <!-- 文案提示条件：加载完成 && 没有数据 -->
      <SjTip v-show="finished && list.length===0" :tip-str="'还没有审核记录哦~'"></SjTip>
      <div slot="loading"></div>
      <div class="list">
        <div v-for="item in list" :key="item.id" class="item">
          <!-- 已同意 -->
          <span
            v-show="checkedIndex === 1"
            :class="`status-${item.status} status-txt`"
          >{{ item.status === 0 ? '上级审核中': item.status === 1 ? '终审已通过': '已拒绝' }}</span>
          <!-- 待审核、已拒绝 -->
          <span
            v-show="checkedIndex !== 1"
            :class="`status-${item.status} status-txt`"
          >{{ item.status === 0 ? '待审核': item.status === 1 ? '已同意': '已拒绝' }}</span>
          <div class="key-wrap">
            <div class="key-name">访客姓名</div>
            <div class="key-value">{{ item.visitorName }}</div>
          </div>
          <div class="key-wrap">
            <div class="key-name">访客电话</div>
            <div class="key-value">{{ item.visitorPhone }}</div>
          </div>
          <div class="key-wrap">
            <div class="key-name">访客身份证</div>
            <div class="key-value">
              {{ item.visitorIdCardNumber ? item.visitorIdCardNumber.replace(/(\d{6})\d*([0-9a-zA-Z]{4})/, '$1********$2') : '未填写' }}
            </div>
          </div>
          <div class="key-wrap">
            <div class="key-name">访客健康码</div>
            <div
              class="key-value"
              :style="`color: ${item.healthCodeColor}`"
              @click="showCodeImage(item.healthCode, item.visitorHealthCodeRefreshTime)"
            >
              {{ item.healthCodeStr }}</div>
          </div>
          <div v-if="item.interviewedName" class="key-wrap">
            <div class="key-name">拜访员工</div>
            <div class="key-value">{{ item.interviewedName }}</div>
          </div>
          <div class="key-wrap">
            <div class="key-name">预约时间</div>
            <div class="key-value">{{ item.beginTime }} 至 <br>{{ item.endTime }}</div>
          </div>
          <div v-if="item.alongWith" class="key-wrap">
            <div class="key-name">随行人数</div>
            <div class="key-value">{{ item.alongWith }}</div>
          </div>
          <div v-if="item.visitorReason" class="key-wrap">
            <div class="key-name">访问事由</div>
            <div class="key-value">{{ item.visitorReason }}</div>
          </div>
          <div v-if="item.carNumber" class="key-wrap">
            <div class="key-name">车辆信息</div>
            <div class="key-value">{{ item.carNumber }}</div>
          </div>
          <div v-if="item.carNumber" class="key-wrap">
            <div class="key-name">车辆进出</div>
            <div class="key-value button">
              <van-switch v-if="checkedIndex === 0" v-model="item.allowCar" size="20px" style="margin-right:10px;" />
              {{ item.allowCar ? '允许' : '拒绝' }}
            </div>
          </div>
          <div v-if="item.status === 2" class="key-wrap">
            <span class="key-name">拒绝理由</span>
            <span class="key-value">{{ item.rejectReason || '未知' }}</span>
          </div>
          <div class="key-wrap">
            <span class="key-name">访问状态</span>
            <span class="key-value">{{ item.visitStatusStr }}
              <span v-if="item.visitStatus === 7 || item.visitStatus === 8" style="color: #267eff;margin-left:10px;" @click="logout(item.id)">点击签离</span>
            </span>
          </div>

          <div v-show="checkedIndex === 0" class="btn-wrap">
            <div class="btn-left" @click="userHandle(item.id, true, item.allowCar)"><span>同意</span></div>
            <div class="btn-right" @click="userHandle(item.id, false)"><span>拒绝</span></div>
          </div>
        </div>
      </div>
    </van-list>

    <SjAudit v-if="dialogVisible" @closeDialog="closeDialog"></SjAudit>
    <van-popup v-model="healCodeDialogVisible" closeable>
      <div class="heal-wrap">
        <div class="time">{{ healInfo.time }}</div>
        <img :src="healInfo.img">
        <div class="status" :style="`color: ${healInfo.color}`">健康状态</div>
      </div>
    </van-popup>

    <div
      v-if="getUnitInfo().name === '江南中学访客系统'"
      class="invite-box"
      :data-clipboard-text="shareUrl"
      @click="copyShareUrl"
    >
      邀请
    </div>

  </div>
</template>

<script>
import vant from 'vant'
import { List, Popup, Switch } from 'vant'
import SjTip from '@/components/SjTip/index.vue'
import SjAudit from '@/components/SjAudit/index.vue'
import { visitFlowPageAPI, visitFlowAuthorizeAPI, visitFlowLeaveAPI } from '@/axios/api/visitor'
import commonUtils from '@/utils/common.js'
import Clipboard from 'clipboard'
export default {
  components: {
    SjAudit,
    SjTip,
    'van-list': List,
    'van-popup': Popup,
    'van-switch': Switch
  },
  data() {
    return {
      healCodeDialogVisible: false,
      healInfo: {
        time: '',
        img: '',
        code: '',
        color: ''
      },
      dialogVisible: false,
      filterList: ['待审核', '已同意', '已拒绝'],
      visitorNameOrPhone: '', // 搜索关键词
      checkedIndex: 0, // tab索引

      unitId: '', // 单位Id
      current: 1,
      total: 0,
      list: [],

      loading: false,
      finished: false,
      flowId: '', // 预约id
      shareUrl: ''
    }
  },
  created() {
    document.title = this.getUnitInfo().name
    this.unitId = localStorage.getItem('visitorH5_unitId')
    this.getList()
  },
  methods: {
    // 关键字
    searchInput(e) {
      this.visitorNameOrPhone = e.target.value.replace(/\s*/g, '')
    },
    // 搜索
    keyWordSearch() {
      if (commonUtils.click_busy()) return
      this.resetData()
    },
    // 切换选项
    changeFilter(i) {
      if (this.checkedIndex === i) return
      if (this.loading) return
      this.checkedIndex = i
      this.resetData()
    },
    // 重置数据
    resetData() {
      this.finished = false
      this.current = 1
      this.total = 0
      this.list = []
      this.getList()
    },
    // 获取列表
    getList() {
      this.loading = true
      vant.Toast.loading({
        duration: 400,
        message: '加载中'
      })
      console.log(`加载第${this.current}页`)
      const params = {
        unitId: this.unitId,
        current: this.current,
        status: this.checkedIndex,
        visitorNameOrPhone: this.visitorNameOrPhone
      }
      visitFlowPageAPI(params).then(res => {
        res.records.forEach((v, i) => {
          v.healthCodeStr = this.dealhealthCodeStr(v.healthCode)
          v.healthCodeColor = this.dealhealthCodeColor(v.healthCode)
          v.visitStatusStr = this.dealVisitStatusStr(v.visitStatus)
          if (v.carNumber && this.checkedIndex === 0) { // 有车辆的，默认允许通行
            v.allowCar = true
          }
        })
        this.list.push(...res.records)
        // 判断--是否已全部加载
        this.total = res.total
        if (this.list.length === this.total) {
          this.finished = true
          console.log('已加载全部')
        } else {
          this.current = this.current + 1
        }
        this.loading = false
      }).catch(res => {
        this.loading = false
        this.finished = true
      })
    },
    // loading为true时，onLoad失效（保证触底时 只进行一次分页）
    onLoad() {
      console.log('检测到触底，继续请求')
      setTimeout(() => {
        this.getList()
      }, 500)
    },
    // 点击--同意 or 拒绝
    userHandle(id, pass, allowCar) {
      this.flowId = id
      pass ? this.submit(true, '', allowCar) : (this.dialogVisible = true)
    },
    // 关闭弹窗
    closeDialog(value) {
      value.refuse ? this.submit(false, value.reason) : (this.dialogVisible = false)
    },
    // 最终提交
    submit(pass, reason, allowCar) {
      if (commonUtils.click_busy()) return
      const params = {
        flowId: this.flowId,
        pass: pass, // 同意 or 拒绝
        reason: reason,
        allowCar: allowCar // 车辆是否通行
      }
      visitFlowAuthorizeAPI(params).then(() => {
        vant.Toast.success({
          duration: 1000,
          message: '提交成功'
        })
        setTimeout(() => {
          this.dialogVisible = false
          this.resetData()
        }, 1000)
      }).catch(res => {
        vant.Toast(res.data.detail || '提交失败')
      })
    },
    // 健康码颜色
    dealhealthCodeColor(code) {
      let color = ''
      switch (code) {
        case 0:
          color = '' // 未获取
          break
        case 1:
          color = '#52C41A' // 绿
          break
        case 2:
          color = '#FF9E3D' // 黄
          break
        case 3:
          color = '#D73232' // 红
          break
      }
      return color
    },
    // 健康码文案
    dealhealthCodeStr(code) {
      let str = ''
      switch (code) {
        case 0:
          str = '未知'
          break
        case 1:
          str = '绿码'
          break
        case 2:
          str = '黄码'
          break
        case 3:
          str = '红码'
          break
      }
      return str
    },
    // 签离状态文案
    dealVisitStatusStr(status) {
      let str = ''
      switch (status) {
        case 0:
          str = '未到访'
          break
        case 5:
          str = '超期自动签离'
          break
        case 6:
          str = '已签离'
          break
        case 7:
          str = '超期未签离'
          break
        case 8:
          str = '已到达'
          break
      }
      return str
    },
    showCodeImage(code, time) {
      if (code !== 0) {
        this.healInfo.time = time
        this.healInfo.img = require(`../../assets/image/banner/code${code}.png`)
        this.healInfo.code = code
        switch (code) {
          case 1:
            this.healInfo.color = '#55AB6B'
            break
          case 2:
            this.healInfo.color = '#ffb341'
            break
          case 3:
            this.healInfo.color = '#ff4141'
            break
        }
        this.healCodeDialogVisible = true
      }
    },
    copyShareUrl() {
      const isPublic = commonUtils.getQueryStringByName('code')
      const userInfo = JSON.parse(localStorage.getItem('visitorH5_userInfo'))
      if (isPublic) {
        this.shareUrl = this.getUnitInfo().publicUrl.slice(0, -1) + userInfo.phone
      } else {
        this.shareUrl = this.getUnitInfo().H5Url.slice(0, -1) + userInfo.phone
      }
      const clipboard = new Clipboard('.invite-box')
      clipboard.on('success', function(e) {
        vant.Toast('邀请链接已复制，快去分享吧')
        e.clearSelection()
      })
      clipboard.on('error', function(e) {
        vant.Toast('链接复制失败')
      })
    },
    // 点击签离
    logout(id) {
      vant.Dialog.confirm({
        title: '确认签离吗？'
      }).then(() => {
        visitFlowLeaveAPI({ flowId: id, unitId: this.unitId }).then(() => {
          vant.Toast.success('签离成功')
          this.resetData()
        }).catch(res => {
          vant.Toast(res.data.detail || '签离失败')
        })
      })
        .catch(() => {
          // on cancel
        })
    }
  }
}
</script>
<style lang="scss" >
.order-list {
  .van-popup {
    width: 100%;
    padding: 0 15px;
    background: transparent;
    .van-popup__close-icon--top-right {
      right: 30px;
    }
  }
  .heal-wrap {
    padding: 10px 64px 10px;
    background: #fff;
    border-radius: 8px;
    .time {
      line-height: 47px;
      font-size: 15px;
      text-align: center;
    }
    img {
      display: block;
      width: 100%;
    }
    .status {
      line-height: 47px;
      font-size: 15px;
      text-align: center;
    }
  }
}
</style>

<style lang="scss" scoped>
@mixin w-h($width, $height) {
  width: $width;
  height: $height;
}
@mixin font-s-w-c($size, $weight, $color) {
  font-size: $size;
  font-weight: $weight;
  color: $color;
}
@mixin flex-config($justify-content, $align-items) {
  display: flex;
  justify-content: $justify-content;
  align-items: $align-items;
}

.top {
  @include w-h(100%, 0);
  padding-bottom: 96px;
  .topfix {
    position: fixed;
    z-index: 100;
    top: 0;
    left: 0;
    @include w-h(100%, 96px);
    background: #ffffff;
    box-shadow: 0px 3px 6px rgba(128, 90, 90, 0.1);

    .search-wrap {
      height: 48px;
      padding: 12px 4px 8px 15px;
      @include flex-config(flex-start, center);
      .search-box {
        @include w-h(calc(100% - 60px), 28px);
        padding: 0 16px;
        border: 1px solid #c6c9cc;
        border-radius: 16px;
        @include flex-config(flex-start, center);
        .search-icon {
          margin-right: 8px;
          @include w-h(16px, 16px);
        }
        input {
          @include flex-config(flex-start, center);
          @include w-h(calc(100% - 24px - 24px), 26px);
          font-size: 12px;
        }
        .clear-icon {
          margin-left: 8px;
          @include w-h(16px, 16px);
        }
      }
      .search-btn {
        width: 60px;
        @include flex-config(center, center);
        @include font-s-w-c(14px, 500, #267eff);
      }
    }

    .filter-wrap {
      padding: 12px 15px 8px;
      @include w-h(100%, 48px);
      @include flex-config(flex-start, flex-start);
      .filter-item {
        margin-right: 16px;
        @include w-h(80px, 28px);
        span {
          @include flex-config(center, center);
          @include w-h(80px, 28px);
          @include font-s-w-c(12px, 500, #a8a8a8);
          text-align: center;
          border: 1px solid #c6c9cc;
          border-radius: 16px;
        }
        .filter-checked {
          color: #267eff;
          border: none;
          background: #f0f7ff;
        }
      }
    }
  }
}

.list {
  padding: 12px 15px 0;
  .item:last-child {
    margin-bottom: 0 !important;
  }
  .item {
    position: relative;
    width: 100%;
    margin-bottom: 12px;
    padding: 24px 15px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0px 3px 6px rgba(38, 126, 255, 0.16);

    .status-txt {
      position: absolute;
      top: 12px;
      right: 12px;
      height: 20px;
      text-align: right;
      font-size: 14px;
    }
    .status-0 {
      color: #ff9e3d !important;
    }
    .status-1 {
      color: #52c41a !important;
    }
    .status-2 {
      color: #a8a8a8 !important;
    }

    .key-wrap {
      margin-top: 12px;
      width: 100%;
      @include flex-config(flex-start, flex-start);
      .key-name {
        min-width: 92px;
        line-height: 20px;
        @include w-h(92px, 20px);
        @include font-s-w-c(14px, 400, #707070);
      }
      .key-value {
        line-height: 20px;
        @include font-s-w-c(14px, 400, #141e2a);
      }
      .button {
        @include flex-config(flex-start, center);
      }
    }
    .key-wrap:nth-child(1) {
      margin-top: 0 !important;
    }

    .btn-wrap {
      margin-top: 17px;
      padding: 0 15px;
      @include flex-config(space-between, flex-start);

      div {
        @include w-h(120px, 32px);
        span {
          @include w-h(120px, 32px);
          font-size: 15px;
          border-radius: 24px;
          @include flex-config(center, center);
        }
      }
      .btn-left span {
        color: #267eff;
        border: 1px solid #267eff;
      }
      .btn-right span {
        color: #a8a8a8;
        border: 1px solid #a8a8a8;
      }
    }
  }
}

.invite-box {
  position: fixed;
  right: 15px;
  bottom: 30px;
  @include w-h(70px, 40px);
  @include font-s-w-c(14px, 400, #267eff);
  @include flex-config(center, center);
  background: #f0f7ff;
  border-radius: 30px;
  box-shadow: 0px 3px 6px rgba(128, 90, 90, 0.1);
  animation: invite-animation 1.2s infinite;

  #selector {
    position: absolute;
    opacity: 0;
    @include w-h(1px, 1px);
    overflow: hidden;
  }
}
@keyframes invite-animation {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}
</style>
